package com.itianyu.blog.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itianyu.blog.dao.beans.Tag;
import com.itianyu.blog.dao.interfaces.TagInterface;

/**
 * 标签控制层
 * @author wumgji
 */
@Controller
@RequestMapping("/tag")
public class TagController {

	@Autowired
	private TagInterface tagInterface;

	// 显示标签列表
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	@ResponseBody
	public List<Tag> listTags() throws Exception {
		return tagInterface.findTagEntities();
	}

	// 显示已发布博文总数以及对应的标签
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	@ResponseBody
	public List<Object[]> tagEntryCount() throws Exception {
		return tagInterface.findTagEntitiesAndEntryCount();
	}

	// 保存标签信息（tagId参数作用仅是保持url一致性）
	@RequestMapping(value = "/save", method = RequestMethod.GET, params = { "tagId", "tagname" })
	@ResponseBody
	public List<Object> saveTag(@RequestParam("tagId") int tagId, @RequestParam("tagname") String tagname) throws Exception {
		Tag tag = null;

		ArrayList<Object> list = new ArrayList<Object>();
		String decodeTagName = new String(tagname.getBytes("ISO-8859-1"), "UTF-8");

		if (tagId >= 0) {
			tag = tagInterface.findTag(tagId);
			if (tag != null) {
				tag.setTagname(decodeTagName);
				tag.setModificationDate(new Date());
			} else {
				list.add("Save failed... Can not find Tag with tagId <" + decodeTagName + ">.");
				return list;
			}
		} else {
			tag = tagInterface.createTag();
			tag.setTagname(decodeTagName);
			tag.setCreationDate(new Date());
			tag.setModificationDate(new Date());
		}

		tag = tagInterface.saveTag(tag);

		list.add("Tag <" + tag.getTagname() + "> successfully saved.");
		return list;
	}

	// 根据标签ID删除标签信息
	@RequestMapping(value = "/delete", method = RequestMethod.GET, params = { "tagId" })
	@ResponseBody
	public List<Object> deleteTag(@RequestParam("tagId") int tagId) throws Exception {
		tagInterface.deleteTag(tagId);

		ArrayList<Object> list = new ArrayList<Object>();
		list.add("成功删除标签");
		return list;
	}

}
